<template>
	<uni-nav-bar
		v-if="!sheep.$store('app').isWxBrowser"
		left-icon="left"
		title="西湖一号丝巾选品平台"
		height="100rpx"
		fixed
		@clickLeft="goBack"
	/>
	<view class="login-container">
		<view class="logo-info">
			<img class="image" src="../../static/common/logo1.png" />
		</view>
		<view class="show-text"> 海量丝巾款式 尽在这里！ </view>
		<view class="login-form">
			<view class="title-area">
				<view class="tip-text"> {{ tipTitle }}</view>
				<view class="sim-code" @click="simCodeLogin">{{ simCodeTitle }}</view>
			</view>
			<!-- 表单 -->
			<uni-forms ref="valiForm" :rules="rules" :modelValue="formData">
				<!-- ====账号密码登录===== -->
				<!-- 账号 -->
				<uni-forms-item name="name" class="form-detail" v-if="switchBtn">
					<view class="change-item-row" required>
						<uni-easyinput
							type="text"
							class="input-detail"
							v-model.trim="formData.name"
							placeholder="请输入用户名或邮箱"
							:inputBorder="false"
						/>
					</view>
				</uni-forms-item>
				<!-- 密码 -->
				<uni-forms-item name="password" class="form-detail password-lie" v-if="switchBtn">
					<view class="change-item-row">
						<uni-easyinput
							type="password"
							class="input-detail"
							:maxlength="20"
							v-model="formData.password"
							placeholder="请输入密码"
							:inputBorder="false"
						/>
					</view>
				</uni-forms-item>

				<!-- ====验证码登录===== -->
				<uni-forms-item name="phone" class="form-detail" v-if="!switchBtn">
					<view class="change-item-row">
						<uni-easyinput
							type="text"
							maxlength="11"
							trim="all"
							class="input-detail"
							v-model.trim="formData.phone"
							placeholder="请输入手机号"
							:inputBorder="false"
							@input="onPhoneInput"
						/>
					</view>
					<!-- 手机号 -->
				</uni-forms-item>
				<!-- 验证码 -->
				<uni-forms-item name="code" class="form-detail password-lie" v-if="!switchBtn">
					<view class="two-columns">
						<view class="password-input">
							<uni-easyinput
								type="text"
								maxlength="4"
								trim="all"
								v-model="formData.code"
								placeholder="请输入验证码"
								:inputBorder="false"
							/>
						</view>
						<!-- fa'so -->
						<button
							class="sim-code-btn"
							:style="btnFlag ? 'background: #111111;' : 'background: #acaeaf;'"
							:disabled="countdownInfo.isDisabled"
							@click="getSimCode"
						>
							{{ showButtonText(countdownInfo.buttonText) }}
						</button>
					</view>
				</uni-forms-item>
			</uni-forms>
			<view class="form-detail submit-btn" @click="toLogin">登录</view>
			<checkbox-group class="check-agreement" @change="checkBoxChange">
				<checkbox
					class="check-box-btn"
					value="1"
					activeBorderColor="#111111"
					activeBackgroundColor="#1111111A"
					iconColor="#111"
					backgroundColor="#fff"
					borderColor="#B7B9BAFF"
				>
					<view class="agreement-text">
						已阅读并接受
						<a
							class="text"
							href="javascript:0"
							@tap="
								(e) => {
									jumper(e, '/pages/index/serviceAgreement');
								}
							"
							>服务协议、</a
						>
						<a
							class="text"
							href="javascript:0"
							@tap="
								(e) => {
									jumper(e, '/pages/index/privacyAgreement');
								}
							"
							>隐私协议</a
						>
					</view>
				</checkbox>
			</checkbox-group>
		</view>
	</view>
</template>

<script setup>
	import { ref, reactive, watch } from 'vue';
	import moment from 'moment';
	import { onHide, onShow, onUnload, onReady } from '@dcloudio/uni-app';
	import sheep from '@/sheep';
	import userApi from './../../sheep/api/user.js';
	import Md5 from 'md5';

	const formData = reactive({
		name: '',
		password: '',
		phone: '',
		code: '',
	});
	const valiForm = ref('');
	const rules = ref({
		name: {
			rules: [
				{
					required: true,
					errorMessage: '请输入用户名或邮箱',
					trigger: 'blur',
				},
			],
		},
		password: {
			rules: [
				{
					required: true,
					errorMessage: '请输入密码',
					trigger: 'blur',
				},
			],
		},
		phone: {
			rules: [
				{
					required: true,
					errorMessage: '请输入手机号',
					trigger: 'blur',
				},
				{
					format: 'number',
					errorMessage: '手机号只能输入数字',
				},
				{
					validateFunction: function (rule, value, data, callback) {
						if (!/^1[3-9]\d{9}$/.test(value)) {
							callback('手机号码格式不正确');
						}
						return true;
					},
				},
			],
		},
		code: {
			rules: [
				{
					required: true,
					errorMessage: '请输入验证码',
					trigger: 'blur',
				},
				{
					format: 'number',
					errorMessage: '验证码只能输入数字',
				},
			],
		},
	});

	const tipTitle = ref('账号密码登录');
	const simCodeTitle = ref('验证码登录');

	const switchBtn = ref(true);

	const simCodeLogin = () => {
		switchBtn.value = !switchBtn.value;
	};
	const isCheckedBox = ref([]);
	const checkBoxChange = (v) => {
		isCheckedBox.value = [...v.detail.value];
	};
	const btnFlag = ref(false);
	/**
	 * 登录
	 */
	const toLogin = () => {
		if (!isCheckedBox.value.length) {
			return uni.showToast({
				title: '请先勾选服务协议和用户协议',
				icon: 'error',
				mask: true,
			});
		}
		valiForm.value.validate().then((res) => {
			if (switchBtn.value) {
				// 账号密码登录
				const formData_account = {
					name: formData.name,
					password: Md5(`W5l^${formData.password}$5S`),
				};
				userApi.accountLogin(formData_account).then((res) => {
					const result = sheep.$store('user').updateUserData(res.data);
					console.log('result====', result);
					sheep.$router.go('/pages/index/index', {}, { reLaunch: true });
				});
			} else {
				// 验证码登录
				const formData_simCode = {
					phone: formData.phone,
					code: formData.code,
				};
				userApi.smsCodeLogin(formData_simCode).then((res) => {
					sheep.$store('user').updateUserData(res.data);
					sheep.$router.go('/pages/index/index', {}, { reLaunch: true });
				});
			}
			if (!isCheckedBox.value.length) {
				return uni.showToast({
					title: '请先勾选服务协议和用户协议',
					icon: 'error',
					mask: true,
				});
			}
		});
	};

	watch([switchBtn], (newValue) => {
		if (newValue[0]) {
			tipTitle.value = '账号密码登录';
			simCodeTitle.value = '验证码登录';
		} else {
			tipTitle.value = '验证码登录';
			simCodeTitle.value = '账号密码登录';
		}
	});
	//倒计时
	const countdownInfo = ref({
		buttonText: '',
		isDisabled: false,
	});
	const hideTimeStamp = ref(null);
	const countDownTimer = ref(null);

	/**
	 * 发送验证码
	 */
	const getSimCode = () => {
		if (!formData.phone) {
			return uni.showToast({
				title: '请先输入手机号',
				icon: 'error',
				mask: true,
			});
		}
		if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
			return uni.showToast({
				title: '手机号码格式不正确',
				icon: 'error',
				mask: true,
			});
		}
		countdownInfo.value.isDisabled = true;
		startCountdownTimer();
		let data = {
			phone: formData.phone,
		};
		userApi
			.sendSmsCode(data)
			.then((res) => {
				console.log(res);
			})
			.catch((err) => {
				console.log(err);
			});
	};
	// 开始倒计时
	const startCountdownTimer = () => {
		btnFlag.value = true;
		countdownInfo.value.buttonText = 60;
		endCountDownTimer();
		countDownTimer.value = setInterval(() => {
			countdownInfo.value.buttonText -= 1;
			if (countdownInfo.value.buttonText === 0) {
				countdownInfo.value.isDisabled = false;
				endCountDownTimer();
			}
		}, 1000);
	};
	// 清空计时器
	const endCountDownTimer = () => {
		clearInterval(countDownTimer.value);
		countDownTimer.value = null;
	};
	const showButtonText = (val) => {
		if (val <= countdownInfo.value.buttonText && !val) {
			return '获取验证码';
		} else {
			return val + 's后可再次获取';
		}
	};
	onHide(() => {
		hideTimeStamp.value = moment().valueOf();
		endCountDownTimer();
	});
	//配合自定义表单校验
	onReady(() => {
		// valiForm.value.setRules(rules);
	});
	onShow(() => {
		if (countdownInfo.value.buttonText > 0 && hideTimeStamp.value) {
			const diffTime = moment().diff(hideTimeStamp.value, 'second');
			if (countdownInfo.value.buttonText - diffTime > 0) {
				countdownInfo.value.buttonText = countdownInfo.value.buttonText - diffTime;
				startCountdownTimer();
			} else {
				countdownInfo.value.buttonText = 0;
				endCountDownTimer();
			}
		}
	});
	onUnload(() => {
		endCountDownTimer();
	});
	const jumper = (e, path) => {
		e.preventDefault();
		sheep.$router.go(path);
	};
	const goBack = () => {
		sheep.$router.back();
	};
	/**
	 * 手机号input change事件
	 */
	const onPhoneInput = (e) => {
		// console.log(e);
		btnFlag.value = /^1[3-9]\d{9}$/.test(e);
	};
</script>
<style scoped lang="scss">
	.login-container {
		height: calc(100vh - 100rpx);
		background-image: url('../../static/common/loginBg.png');
		background-repeat: no-repeat;
		background-size: 100% 100%;
		overflow: hidden;
		padding: 0 32rpx;

		.logo-info {
			width: 220rpx;
			height: 64rpx;
			margin-top: 48rpx;

			.image {
				width: 100%;
				height: 100%;
			}
		}

		.show-text {
			width: 470rpx;
			height: 56rpx;
			margin-top: 32rpx;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			font-size: 40rpx;
			color: #ffffff;
			line-height: 56rpx;
			text-align: left;
			font-style: normal;
		}

		.login-form {
			width: 686rpx;
			height: 610rpx;
			position: absolute;
			top: 70%;
			left: 50%;
			transform: translate(-50%, -50%);
			background: #ffffff;
			box-shadow: 0px 50rpx 30rpx -50rpx rgba(17, 17, 17, 0.15);
			border-radius: 48rpx;
			border: 2rpx solid #ffffff;
			backdrop-filter: blur(5rpx);

			.title-area {
				width: 622rpx;
				height: 56rpx;
				margin: 48rpx auto;
				display: flex;
				justify-content: space-between;

				.tip-text {
					width: 250rpx;
					height: 56rpx;
					font-family: PingFangSC, PingFang SC;
					font-weight: 500;
					font-size: 40rpx;
					color: #111111;
					line-height: 56rpx;
					text-align: left;
					font-style: normal;
				}

				.sim-code {
					height: 36rpx;
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 26rpx;
					color: #666666;
					line-height: 36rpx;
					text-align: left;
					font-style: normal;
				}
			}

			.form-detail {
				width: 622rpx;
				height: 90rpx;
				margin: 0 auto;
				background: #eef0f2;
				border-radius: 16rpx;

				.change-item-row {
					margin: 10rpx 0 0 0;

					.input-detail {
						width: 622rpx;
						border: 1px solid #eef0f2;
						display: flex;
						align-items: center;
						box-sizing: border-box;
						padding: 0 32rpx;
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 28rpx;
						color: #bbbbbb;
						line-height: 40rpx;
						font-style: normal;
					}
				}
			}
			.password-lie {
				margin-top: 16rpx;

				.two-columns {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin: 10rpx 0 0 0;
					padding: 0 32rpx;

					.password-input {
						width: 262rpx;
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 28rpx;
						color: #bbbbbb;
						line-height: 40rpx;
						font-style: normal;
					}

					.sim-code-btn {
						height: 58rpx;
						border-radius: 8rpx;
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 24rpx;
						color: #ffffff;
						line-height: 58rpx;
						text-align: justify;
						font-style: normal;
						//解决flex布局，两端对齐不生效
						position: absolute;
						right: 26rpx;
					}
				}
			}

			.submit-btn {
				margin-top: 64rpx;
				height: 100rpx;
				background: #111111;
				border-radius: 50rpx;
				font-family: PingFangSC, PingFang SC;
				font-weight: 500;
				font-size: 32rpx;
				color: #ffffff;
				line-height: 44rpx;
				letter-spacing: 1px;
				text-align: center;
				line-height: 100rpx;
				font-style: normal;
			}

			.check-agreement {
				height: 38rpx;
				text-align: center;
				margin-top: 16rpx;

				.check-box-btn {
					transform: scale(0.72);
					height: 36rpx;
					text-align: center;
					padding: 0 32rpx;
					:deep(.uni-checkbox-input) {
						& > svg {
							border-radius: 50%;
							width: 30rpx;
							height: 30rpx;
							background: #111;
							color: #111;
						}
						border-radius: 50%;
						width: 40rpx;
						height: 40rpx;
					}

					.agreement-text {
						height: 34rpx;
						margin-left: 6rpx;
						font-family: PingFangSC, PingFang SC;
						font-weight: 400;
						font-size: 32rpx;
						color: #666666;
						line-height: 34rpx;
						text-align: left;
						font-style: normal;

						a {
							color: #ff6c01;
							text-decoration: none;
						}
					}
				}

				.text {
					font-size: 32rpx;
				}
			}
		}
		:deep(.uni-forms-item__inner) {
			padding-bottom: 0;
		}
	}
</style>
